package com.hejia.bulbul.controller;

import com.hejia.alauda.entity.*;
import com.hejia.alauda.entity.example.RedpacketExample;
import com.hejia.alauda.service.AccountService;
import com.hejia.alauda.service.CreditService;
import com.hejia.alauda.service.RedEnvelopeService;
import com.hejia.alauda.service.UserService;
import com.hejia.alauda.utils.Pager;
import com.hejia.alauda.utils.PagerHelper;
import com.hejia.alauda.utils.Utils;
import com.hejia.bulbul.entity.DataTablesReturnObject;
import com.hejia.bulbul.entity.JSONParam;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("redpacket")
public class RedpacketController extends BaseController {
	private final Log logger = LogFactory.getLog(getClass());

	@Resource
	private RedEnvelopeService redEnvelopeService;

	@Resource
	private CreditService service;

	@Resource
	private UserService userService;

	@Resource
	private AccountService accountService;

	/**
	 * 红包记录展示页
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String red(ModelMap model, Pager<BonusRecord> pager) {
		service.bonusRecordPager(pager);
		RedpacketExample example = new RedpacketExample();
		Pager<Redpacket> redPacket = redEnvelopeService.findAllRedpacket(
				new Pager<Redpacket>(), example);

		List<Redpacket> list = redPacket.getList();

		for (int i = 0; i < pager.getList().size(); i++) {
			for (Redpacket redpacket : list) {
				if (pager.getList().get(i).getCode()
						.equals(redpacket.getCode())) {
					pager.getList().get(i).setCode(redpacket.getName());
					break;
				}
			}
		}

		model.put("pager", pager);

		PagerHelper<BonusRecord> helper = new PagerHelper<>();
		helper.setBaseUrl("/redpacket");
		helper.setPager(pager);

		model.put("helper", helper);

		return "/redpacket/red";
	}

	/**
	 * 添加红包记录页面
	 */
	@RequestMapping(value = "release", method = RequestMethod.GET)
	public String redPacketRelease(ModelMap model, Pager<Redpacket> pager) {
		Pager<Redpacket> redPacket = redEnvelopeService.findAllRedpacket(pager);
		model.put("redpacket", redPacket);
		return "/redpacket/red_add";
	}

	/**
	 * 添加红包记录
	 */
	@RequestMapping(value = "release", method = RequestMethod.POST)
	public String addBonusRecord(RedirectAttributes redirectAttributes,
			HttpServletRequest request) {
		InputStream is = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> items = upload.parseRequest(request);
			int success = 0;
			BonusRecord bonusRecord = new BonusRecord();
			bonusRecord.setUser(new User());
			String code = "";
			int term = 0;
			BigDecimal amount = BigDecimal.ZERO;
			String description = "";
			String type = "";
			String mobiles = "";
			String expiredDate = "";
			for (FileItem item : items) {
				if (item.isFormField()) {
					if ("description".equals(item.getFieldName())) {
						description = item.getString("utf-8");
					} else if ("amount".equals(item.getFieldName())) {
						amount = BigDecimal.valueOf(Integer.parseInt(item
								.getString("utf-8")));
					} else if ("mobiles".equals(item.getFieldName())) {
						mobiles = item.getString("utf-8");
					} else if ("code".equals(item.getFieldName())) {
						code = item.getString("utf-8");
						type = code;
					} else if ("term".equals(item.getFieldName())) {
						term = Integer.parseInt(item.getString("utf-8"));
					} else if ("expiredDate".equals(item.getFieldName())) {
						expiredDate = item.getString("utf-8");
					}

				} else {
					is = item.getInputStream();
				}
			}

			BufferedReader dr = new BufferedReader(new InputStreamReader(is));
			String mobile = "";
			// 读取流到 mobile 里
			while (mobile != null) {
				mobile = dr.readLine();
				if (mobile == null) {
					break;
				}
				System.out.println(mobile);
				User user = userService.findUserByMobile(mobile);
				if (user != null && !"".equals(user.getMobile())) {
					UserDetails currentAccount = this.accountService
							.getCurrentAccount();
					String operator = null;
					if (currentAccount != null) {
						operator = currentAccount.getUsername();
					}
					if (service.giveBonus(user.getId(), code, term, amount,
							description, type, operator)) {
						success++;
					}
				}
			}
			dr.close();
			is.close();
			if (mobiles != null) {
				String[] arrMobile = mobiles.split(",");
				for (int i = 0; arrMobile != null && i < arrMobile.length; i++) {
					User user = userService.findUserByMobile(arrMobile[i]);
					if (user != null && !"".equals(user.getMobile())) {
						UserDetails currentAccount = this.accountService
								.getCurrentAccount();
						String operator = null;
						if (currentAccount != null) {
							operator = currentAccount.getUsername();
						}
						if (service.giveBonus(user.getId(), code, term, amount,
								description, type, operator)) {
							success++;
						}
					}
				}
			}
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", success + "红包添加成功");
		} catch (Exception e) {
			logger.error("添加红包失败！" + Utils.getExceptionLog(e));
			e.printStackTrace();
		}

		return "redirect:/redpacket";
	}

	@RequestMapping(value = "allredpacket", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> allPacket(ModelMap model, Pager<Redpacket> pager) {
		pager.setPageSize(Integer.MAX_VALUE);
		Pager<Redpacket> redPacket = redEnvelopeService.findAllRedpacket(pager);
		redPacketList(model, pager);
		Map<String, Object> map = new HashMap<>();
		map.put("list", redPacket.getList());
		return map;
	}

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String redPacketList(ModelMap model, Pager<Redpacket> pager) {
		Pager<Redpacket> redPacket = redEnvelopeService.findAllRedpacket(pager);
		model.put("redpacket", redPacket);
		return "/redpacket/redpacket_list";
	}

	/**
	 * 跳转到添加界面
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String addRedPacket() {
		return "/redpacket/redpacket_input";
	}

	/**
	 * 添加完保存
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String saveRedpacket(Redpacket redpacket,
			RedirectAttributes redirectAttributes) {
		if (redEnvelopeService.saveRedpacket(redpacket)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "红包管理添加成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "红包管理添加失败");
		}

		return "redirect:/redpacket/list";
	}

	/**
	 * 跳转到修改界面
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateRedpacket(@PathVariable Long id, ModelMap model) {
		Redpacket redpacket = redEnvelopeService.getRedpacketById(id);
		model.put("redpacket", redpacket);

		return "/redpacket/redpacket_input";
	}

	/**
	 * 修改完保存
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.POST)
	public String saveUpdateRedPacket(Redpacket redpacket,
			RedirectAttributes redirectAttributes) {
		if (redEnvelopeService.modifyRedpacket(redpacket)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "红包管理修改成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "红包管理修改失败");
		}

		return "redirect:/redpacket/list";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
	public String deleteRedPacket(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		if (redEnvelopeService.deleteRedpacket(id)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "红包管理删除成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "红包管理删除失败");
		}

		return "redirect:/redpacket/list";
	}

	/**
	 * 以ajax格式返回列表请求
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "redpacketAsAjax", method = RequestMethod.POST)
	@ResponseBody
	public DataTablesReturnObject<Redpacket> redPacketAsAjax(
			@RequestBody JSONParam[] params) {
		HashMap<String, String> paramMap = JSONParam.convertToMap(params);

		// 分页信息
		Pager<Redpacket> pager = new Pager<Redpacket>();
		int start = Integer.parseInt(paramMap.get("iDisplayStart"));
		int length = Integer.parseInt(paramMap.get("iDisplayLength"));
		pager.setPageSize(length);
		pager.setPageNumber(start / length + 1);

		// 查询条件
		RedpacketExample exp = new RedpacketExample();

		String sSearch = paramMap.get("sSearch");
		if (StringUtils.isNotEmpty(sSearch)) {
			exp.appendCriterion("name like  ", "%" + sSearch + "%");
		}
		// 排序
		int iSortingCols = Integer.parseInt(paramMap.get("iSortingCols"));
		for (int i = 0; i < iSortingCols; i++) {
			String iSortCol = paramMap.get("iSortCol_" + i);
			String mDataProp = paramMap.get("mDataProp_" + iSortCol);
			String sSortDir = paramMap.get("sSortDir_" + i);
			if (i > 0) {
				exp.setOrderByClause(exp.getOrderByClause() + ",");
				exp.setOrderByClause(exp.getOrderByClause() + mDataProp + " "
						+ sSortDir);
			} else {
				exp.setOrderByClause(mDataProp + " " + sSortDir);
			}
		}

		pager = redEnvelopeService.findAllRedpacket(pager, exp);

		DataTablesReturnObject<Redpacket> dtr = new DataTablesReturnObject<Redpacket>(
				pager.getTotalCount(), paramMap.get("sEcho"), pager.getList());
		return dtr;
	}

}
